package com.rachel.wifimanagerdemo;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SwitchCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.rachel.wifimanagerdemo.adapter.WifiListAdapter;
import com.rachel.wifimanagerdemo.base.BaseViewHolder;

import java.util.List;

import butterknife.BindView;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "WifiSetting";
    private static final int WIFICIPHER_NOPASS = 1;
    private static final int WIFICIPHER_WEP = 2;
    private static final int WIFICIPHER_WPA = 3;
    @BindView(R.id.search_sw)
    SwitchCompat searchSwitch;
    @BindView(R.id.wifi_rv)
    RecyclerView wifiRv;
    private String currentTargetWifi;
    private WifiManager wifiManager;
    private WifiListAdapter wifiListAdapter;
    private WifiConfiguration config;
    private Dialog dialog;
    private TextView contentTv;
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
                Log.d(TAG, "SCAN_RESULTS_AVAILABLE_ACTION");
                List<ScanResult> scanResults = wifiManager.getScanResults();
                wifiListAdapter.updateData(scanResults);
            } else if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
                Log.d(TAG, "WIFI_STATE_CHANGED_ACTION");
                int wifiState = intent.getIntExtra(
                        WifiManager.EXTRA_WIFI_STATE, 0);
                switch (wifiState) {
                    case WifiManager.WIFI_STATE_ENABLED:
                        //获取到wifi开启的广播时，开始扫描
                        wifiManager.startScan();
                        break;
                    case WifiManager.WIFI_STATE_DISABLED:
                        //wifi关闭发出的广播
                        break;
                }
            } else if (action.equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)) {
                int errorCode = intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR, -1);
                if (errorCode == WifiManager.ERROR_AUTHENTICATING) {
//                    ToastUtils.get().showText("密码错误");
                    dismissLoading();
                }
            } else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
                NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                WifiInfo wifiInfo = intent.getParcelableExtra(WifiManager.EXTRA_WIFI_INFO);
                if (info.getState().equals(NetworkInfo.State.DISCONNECTED)) {
                    wifiListAdapter.updateConnectState("-1");
                    Log.d(TAG, "连接已断开");
                } else if (info.getState().equals(NetworkInfo.State.CONNECTED)) {
                    wifiListAdapter.updateConnectState(wifiInfo.getSSID());
                    Log.d(TAG, "已连接到网络:" + wifiInfo.getSSID());
                    if (wifiInfo.getSSID().equals(currentTargetWifi)) {
                        dismissLoading();
                    }
                } else {
                    NetworkInfo.DetailedState state = info.getDetailedState();
                    if (state == state.CONNECTING) {
                        Log.d(TAG, "连接中...");
                        updateLoading("连接中...");
                    } else if (state == state.AUTHENTICATING) {
                        Log.d(TAG, "正在验证身份信息...");
                        updateLoading("正在验证身份信息...");
                    } else if (state == state.OBTAINING_IPADDR) {
                        Log.d(TAG, "正在获取IP地址...");
                        updateLoading("正在获取IP地址...");
                    } else if (state == state.FAILED) {
                        Log.d(TAG, "连接失败");
                        dismissLoading();
//                        ToastUtils.get().showText("连接失败");
                    } else if (state == state.CONNECTED) {
                        Log.e(TAG, "连接失败---------------");
                    }
                }
            }

        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        initView();
        initBroadcastReceiver();
    }

    private void initView() {
        searchSwitch.setChecked(wifiManager.isWifiEnabled());
        wifiRv.setVisibility(wifiManager.isWifiEnabled() ? View.VISIBLE : View.INVISIBLE);
        searchSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                wifiRv.setVisibility(isChecked ? View.VISIBLE : View.INVISIBLE);
                if (isChecked) {
                    search();
                } else {
                    closeWifi();
                }
            }
        });

        wifiRv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        wifiListAdapter = new WifiListAdapter(this);
        wifiRv.setAdapter(wifiListAdapter);

        wifiListAdapter.setOnItemClickLitener(new BaseViewHolder.onItemCommonClickListener() {
            @Override
            public void onItemClickListener(View view, int position) {
                final ScanResult scanResult = wifiListAdapter.getItem(position);
                if (wifiListAdapter.isCurrentConnectItem(scanResult.SSID)) {
                    disconnectWifi(scanResult);
                } else {
                    connectWifi(scanResult);
                }
            }
        });
        wifiListAdapter.setOnLongClickLitener(new BaseViewHolder.onItemCommonLongClickListener() {
            @Override
            public void onItemLongClickListener(View view, int position) {
                showConnectDialog(wifiListAdapter.getItem(position));
            }
        });
    }

    private void connectWifiByCreateConfig(ScanResult scanResult) {
        String capabilities = scanResult.capabilities;
        int type = WIFICIPHER_WPA;
        if (!TextUtils.isEmpty(capabilities)) {
            if (capabilities.contains("WPA") || capabilities.contains("wpa")) {
                type = WIFICIPHER_WPA;
            } else if (capabilities.contains("WEP") || capabilities.contains("wep")) {
                type = WIFICIPHER_WEP;
            } else {
                type = WIFICIPHER_NOPASS;
            }
        }
        if (type != WIFICIPHER_NOPASS) {//需要密码
            final int finalType = type;
//            DialogView dialogView = new DialogView(MainActivity.this);
//            dialogView.setTitle(scanResult.SSID)
//                    .setHint("请输入WiFi密码")
//                    .setEditContent("")
//                    .setClickSureDismissDialog(false)
//                    .setOnClickListener(content -> {
//                        if (content.length() < 8) {
//                            ToastUtils.get().showText("WiFi密码至少为8位");
//                            return;
//                        }
//                        Log.d(TAG, "输入密码：" + content);
//                        config = createWifiInfo(scanResult.SSID, content, finalType);
//                        connect(config);
//                        dialogView.dismiss();
//                    }).show();
        } else {
            config = createWifiInfo(scanResult.SSID, "", type);
            connect(config);
        }
    }

    private void initBroadcastReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);//扫描结果
        intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);//wifi状态，是否连上，密码
        intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);//网络状态变化
        intentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
//        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);//连上与否
//        intentFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);//信号强度变化
        registerReceiver(receiver, intentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }

    /**
     * 判断当前wifi是否有保存
     *
     * @param SSID
     * @return
     */
    private WifiConfiguration isExsits(String SSID) {
        List<WifiConfiguration> existingConfigs = wifiManager.getConfiguredNetworks();
        for (WifiConfiguration existingConfig : existingConfigs) {
            if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
                return existingConfig;
            }
        }
        return null;
    }


    private void showLoading(String content) {
        dialog = new Dialog(MainActivity.this, R.style.DimDialogStyle);
        dialog.setContentView(R.layout.dialog_loading);
        contentTv = (TextView) dialog.findViewById(R.id.content_tv);
        contentTv.setText(content);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(true);
        dialog.show();
    }

    private void updateLoading(String content) {
        if (dialog != null && dialog.isShowing() && contentTv != null) {
            contentTv.setText(content);
        }
    }

    private void dismissLoading() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    private void showConnectDialog(ScanResult scanResult) {
        Dialog connectDialog = new Dialog(MainActivity.this, R.style.DimDialogStyle);
        connectDialog.setContentView(R.layout.dialog_wifi);
        TextView titleTv = (TextView) connectDialog.findViewById(R.id.title_tv);
        titleTv.setText(scanResult.SSID);
        LinearLayout disconnectLl = (LinearLayout) connectDialog.findViewById(R.id.disconnect_ll);
        LinearLayout connectLl = (LinearLayout) connectDialog.findViewById(R.id.connect_ll);
        LinearLayout removeLl = (LinearLayout) connectDialog.findViewById(R.id.remove_ll);
        LinearLayout modifyLl = (LinearLayout) connectDialog.findViewById(R.id.modify_ll);
        WifiConfiguration configuration = isExsits(scanResult.SSID);
        if (wifiListAdapter.isCurrentConnectItem(scanResult.SSID)) {
            disconnectLl.setVisibility(View.VISIBLE);
            removeLl.setVisibility(View.VISIBLE);
            connectLl.setVisibility(View.GONE);
            modifyLl.setVisibility(View.VISIBLE);
        } else if (configuration != null) {
            disconnectLl.setVisibility(View.GONE);
            removeLl.setVisibility(View.VISIBLE);
            connectLl.setVisibility(View.VISIBLE);
            modifyLl.setVisibility(View.VISIBLE);
        } else {
            connectLl.setVisibility(View.VISIBLE);
            disconnectLl.setVisibility(View.GONE);
            removeLl.setVisibility(View.GONE);
            modifyLl.setVisibility(View.GONE);
        }
        connectDialog.setCanceledOnTouchOutside(true);
        connectDialog.setCancelable(true);
        connectDialog.show();
        connectLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                connectDialog.dismiss();
                if (configuration == null) {
                    connectWifi(scanResult);
                } else {
                    connect(configuration);
                }
            }
        });
        disconnectLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                connectDialog.dismiss();
                disconnectWifi(scanResult);
            }
        });
        removeLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                connectDialog.dismiss();
                removeWifi(scanResult);
            }
        });
        modifyLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                connectDialog.dismiss();
                connectWifiByCreateConfig(scanResult);
            }
        });
    }


    public WifiConfiguration createWifiInfo(String SSID, String password,
                                            int type) {
        Log.d(TAG, "SSID = " + SSID + "password " + password + "type ="
                + type);
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + SSID + "\"";
        WifiConfiguration tempConfig = this.isExsits(SSID);
        if (tempConfig != null) {
            wifiManager.removeNetwork(tempConfig.networkId);
        }

        if (type == WIFICIPHER_NOPASS) {
            config.wepKeys[0] = "\"" + "\"";
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        } else if (type == WIFICIPHER_WEP) {
            config.preSharedKey = "\"" + password + "\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms
                    .set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedGroupCiphers
                    .set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedGroupCiphers
                    .set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedGroupCiphers
                    .set(WifiConfiguration.GroupCipher.WEP40);
            config.allowedGroupCiphers
                    .set(WifiConfiguration.GroupCipher.WEP104);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        } else if (type == WIFICIPHER_WPA) {
            config.preSharedKey = "\"" + password + "\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms
                    .set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedGroupCiphers
                    .set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedKeyManagement
                    .set(WifiConfiguration.KeyMgmt.WPA_PSK);
            config.allowedPairwiseCiphers
                    .set(WifiConfiguration.PairwiseCipher.TKIP);
            // config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            config.allowedGroupCiphers
                    .set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedPairwiseCiphers
                    .set(WifiConfiguration.PairwiseCipher.CCMP);
            config.status = WifiConfiguration.Status.ENABLED;
        } else {
            return null;
        }
        return config;
    }

    // 关闭WIFI
    @SuppressLint("WrongConstant")
    public void closeWifi() {
        if (wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(false);
//            ToastUtils.get().showText("Wifi已经关闭");
        } else if (wifiManager.getWifiState() == WifiManager.WIFI_STATE_DISABLED) {
//            ToastUtils.get().showText("Wifi已经关闭");
        } else if (wifiManager.getWifiState() == WifiManager.WIFI_STATE_DISABLING) {
//            ToastUtils.get().showText("Wifi正在关闭");
        } else {
//            ToastUtils.get().showText("请重新关闭");
        }
    }

    /**
     * 搜索wifi热点
     */
    private void search() {
        if (!wifiManager.isWifiEnabled()) {
            //开启wifi
            wifiManager.setWifiEnabled(true);
        }
        wifiManager.startScan();
    }

    private void connectWifi(ScanResult scanResult) {
//        disconnectWifi(scanResult);
        config = isExsits(scanResult.SSID);
        if (config == null) {
            connectWifiByCreateConfig(scanResult);
        } else {
            connect(config);
        }
    }

    /**
     * 建立连接
     *
     * @param config
     */
    private void connect(WifiConfiguration config) {
        currentTargetWifi = config.SSID;
        showLoading("连接中...");
        new Thread(new Runnable() {
            @Override
            public void run() {
                int wcgID = wifiManager.addNetwork(config);
                Log.e(TAG, wcgID + "连接中...");
                if (wcgID == -1) {
//                    ToastUtils.get().showText("连接失败");
                    dismissLoading();
                    return;
                }
                wifiManager.enableNetwork(wcgID, true);
            }
        }).start();
    }

    /**
     * 断开连接
     */
    private void disconnectWifi(ScanResult scanResult) {
        WifiConfiguration configuration = isExsits(scanResult.SSID);
        if (configuration == null) return;
        wifiManager.disableNetwork(configuration.networkId);
        wifiManager.disconnect();
    }

    /**
     * 不保存网络
     */
    private void removeWifi(ScanResult scanResult) {
        WifiConfiguration configuration = isExsits(scanResult.SSID);
        wifiManager.disableNetwork(configuration.networkId);
        wifiManager.disconnect();
        wifiManager.removeNetwork(configuration.networkId);
    }

}